import sys

import threading
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.Ui_my_main_window import Ui_MainWindow
from drivers.driver_net import NetDriver#导入网络驱动
class MainWindow(QMainWindow):
    
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        
        #加载Ui内容
        self.ui.setupUi(self)
        self.net_driver = NetDriver()#创建网络驱动对象
        
        #将信号连接到槽
        self.net_driver.net_msg_signal.connect(self.on_data_recv_slot)
        self.init_ui()
        
    #更新ui的连接状态
    def update_connect_state(self):
        if not self.net_driver.is_connected():
            #连接网络
            self.ui.btn_connect.setText("连接网络")
            self.ui.btn_connect.setIcon(QIcon(":ic/连接 (2).png"))
        else:
            #断开连接
            self.ui.btn_connect.setText("断开连接")
            self.ui.btn_connect.setIcon(QIcon(":ic/连接 (1).png"))
            
    #更新ui图标信息和槽函数        
    @pyqtSlot(int,object)
    def on_data_recv_slot(self,type_t,msg):
        if type_t == 0:
            self.update_connect_state()
        elif type_t == 1:     
            thread_name = threading.current_thread().name
            print(msg, " thread->", thread_name)   
            self.ui.edit_recv.appendPlainText(msg)
    
    #点击连接按钮    
    @pyqtSlot()    
    def on_btn_connect_clicked(self):#连接
        #再次点击，断开连接
        if self.net_driver.is_connected():
            self.net_driver.disconnect()
            return 
           
        #获取用户输入的ip和端口
        mode = self.ui.cb_mode.currentText()
        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        print(f"连接{mode} {target_ip}:{target_port}")
        
        #启动客户端线程
        self.net_driver.connect_server(target_ip, target_port)
    
    #点击发送按钮    
    @pyqtSlot()   
    def on_btn_send_clicked(self):#发送
        text = self.ui.edit_send.toPlainText()
        if len(text) == 0:
            self.statusBar().showMessage("请先输入要发送的消息！")
            return
        if not self.net_driver.is_connected():
            self.statusBar().showMessage("请先连接服务器！")
            QMessageBox.warning(self, "警告", "请先连接服务器！", QMessageBox.Yes)
            return
        
        # self.tcp_client.send(text.encode())
        self.net_driver.send_msg(text)
        
    #初始化ui 
    def init_ui(self):
        #初始化target_ip和target_port
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8080")
        # self.ui.btn_connect.clicked.connect(self.on_btn_connect_clicked)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywindow = MainWindow()
    mywindow.show()
    sys.exit(app.exec_())